package com.wolfman.uploadfile.components;

import com.wolfman.uploadfile.po.FileUpload;
import com.wolfman.uploadfile.service.FileUploadService;
import com.wolfman.uploadfile.vo.FileVo;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2021/8/22 19:17
 * @Email 2370032534@qq.com
 */
@Component
public final class UploadFileComponent {

    @Resource
    UuidComponent uuidComponent;
    @Resource
    RedisComponent redisComponent;
    @Resource
    FileUploadService fileUploadService;

    /**
     * 上传文件 没有上传到oss中
     *
     * @param file
     * @param Path
     * @param filename
     */
    public void uploadFile(MultipartFile file, String Path, String filename) {
        //设置存储目录的绝对路径
        File filePath = new File(new File("").getAbsolutePath() + Path);
        //判断目录是否存在
        if (!filePath.exists()) {
            //创建目录
            filePath.mkdirs();
        }
        //创建文件
        File finalFilePath = new File(filePath + "/" + filename);
        try {
            //移动文件
            file.transferTo(finalFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 随机生成文件名
     *
     * @return
     */
    public String generateFilename(MultipartFile file) {
        String oldFilename = file.getOriginalFilename();
        int extensionIndex = oldFilename.lastIndexOf(".");
        String extension = oldFilename.substring(extensionIndex);
        return uuidComponent.getUuid() + extension;
    }

    /**
     * 随机生成文件名
     *
     * @return
     */
    public String generateFilename(String filename) {
        int extensionIndex = filename.lastIndexOf(".");
        String extension = filename.substring(extensionIndex);
        return uuidComponent.getUuid() + extension;
    }

    /**
     * 使用随机流上传文件
     *
     * @return
     */
    public void randomAccessUploadFile(FileVo fileVo, String filePath, FileUpload fileUpload, long offset) throws Exception {
        //获取文件流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileVo.getFile().getInputStream());
        RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");
        //记录文件总大小
        double totalSize = fileVo.getTotalSize();
        //未上传的量
        long restSize;
        //偏移位置
        bufferedInputStream.skip(0);
        randomAccessFile.seek(offset);
        //初始化上传进度
        String key = "id:" + fileUpload.getId() + "-percent:";
        if (redisComponent.get(key) == null) {
            redisComponent.set(key, 0d);
        }
        //开启新线程上传文件
        //上传进度
        Double percent;
        //是否暂停
        redisComponent.set("id:" + fileUpload.getId() + "-isPause", false);
        boolean isPause;
        byte[] buffer = new byte[1024];
        //上传文件
        while (bufferedInputStream.read(buffer) != -1) {
            //写入文件
            randomAccessFile.write(buffer);
            Thread.sleep(100);
            //未上传的量
            restSize = fileVo.getTotalSize() - fileVo.getStart() - (fileVo.getCurrentSize() - bufferedInputStream.available());
            //将上传进度记录到redis
            percent = (1 - restSize / totalSize) * 100;
            redisComponent.set(key, percent);
            //获取是否暂停
            isPause = (boolean) redisComponent.get("id:" + fileUpload.getId() + "-isPause");
            if (isPause) {
                //关闭流
                bufferedInputStream.close();
                randomAccessFile.close();
                //记录进度
                fileUpload.setUploadProgress(percent);
                fileUploadService.updateProcess(fileUpload);
                //退出文件上传循环
                return;
            }
        }
        //关闭流
        bufferedInputStream.close();
        randomAccessFile.close();
        //更新进度
        fileUpload.setUploadProgress(100.00D);
        fileUploadService.updateProcess(fileUpload);
    }

}
